<?php
namespace app\user\controller;
use think\Controller;
use think\facade\Request;
use think\captcha\Captcha;
class Login extends Controller{
    protected $sys;
    public function initialize(){
        if (session('user.id')) {
            $this->redirect('index/index');
        }
        $this->sys = cache('System');
        $this->assign('sys',$this->sys);
    }
    public function index(){
        if(request()->isPost()) {
            $table = db('users');
            $username = input('username');
            $password = input('password');
            if($this->sys['code']=='open'){
                $code = input('vercode');
                if(!$this->check($code)){
                    return array('code' => 0, 'msg' => '验证码错误');
                }
            }
            if(!$username || !$password){
                return array('code'=>0,'msg'=>'请填写账号或密码');
            }
            $user = $table->where("nickname",$username)->whereOr('mobile',$username)->find();
            if(!$user){
                return array('code'=>0,'msg'=>'账号不存在!');
            }elseif(md5($password) != $user['password']){

                return array('code'=>0,'msg'=>'密码错误!');
            }elseif($user['is_lock'] == 1){
                return array('code'=>0,'msg'=>'账号异常已被锁定！！！');
            }else{
                $ip = $_SERVER["REMOTE_ADDR"];
                $up_user=array(
                    'last_ip'=>$ip,
                );
                db('users')->where('id',$user['id'])->update($up_user);
                $sessionUser = $table->where("id",'=',$user['id'])->find();
                $openid = db('oauth')->where([['uid','=',$user['id']],['type','=','qq']])->value('openid');
                if($openid){
                    $sessionUser['qq'] = 1;
                }
                session('user',$sessionUser);
                return array('code'=>1,'msg'=>'登录成功','url' => url('index/index'));
            }
        }else{
            $plugin = db('plugin')->where(['type'=>'login','status'=>1])->select();
            $this->assign('plugin', $plugin);
            $this->assign('title','会员登录');
            return $this->fetch();
        }
    }
    public function verify(){
        $config =    [
            // 验证码字体大小
            'fontSize'    =>    25,
            // 验证码位数
            'length'      =>    4,
            // 关闭验证码杂点
            'useNoise'    =>    false,
            'bg'          =>    [255,255,255],
        ];
        $captcha = new Captcha($config);
        return $captcha->entry();
    }

    public function getRegion(){
        $Region=db("region");
        $pid = input("pid");
        $arr = explode(':',$pid);
        $map['pid']=$arr[1];
        $list=$Region->where($map)->select();
        return $list;
    }
    public function check($code){
        return captcha_check($code);
    }
    public function regist(){
        $levellist=db('user_level')->where('level_id','gt',0)->select();
        $this->assign('levels',$levellist);
        $sys=getsystem();
        $this->assign('sys',$sys);
        $bianhao=rand(100000,999999);
        $this->assign('bianhao',$bianhao);
        $id=input('id');
        if(!empty($id)){
            $user=getuser($id);
        }

        $this->assign('mobile', $user['nickname']);

        $inf=db('users')->where('id',1)->find();
        $this->assign('inf',json_encode($inf,true));
        $province = db('Region')->where (array('pid'=>1) )->select();
        $this->assign('province',json_encode($province,true));
        $city = db('Region')->where ( array('pid'=>$inf['province']))->select();
        $this->assign('city',json_encode($city,true));
        $district = db('Region')->where ( array('pid'=>$inf['city']))->select();
        $this->assign('district',json_encode($district,true));
        if(Request::isAjax()) {
            $data = input('post.');
            $username = $data['username'];
            $mobile = $data['mobile'];
            $nickname = $data['nickname'];
            $password = $data['password'];
            $code = $data['code'];
            $twopassword = $data['twopassword'];
            $dizhi = $data['dizhi'];
            $topmobi = $data['topmobi'];
            $centermobile = $data['center_id'];
            $shenfenzheng = $data['shenfenzheng'];
            $fathername = $data['fathername'];
            $treeplace = $data['treeplace'];
            $level = $data['level'];
            $info['level']=1;
            $info['tlevel']=0;

            if($sys['code']=='open'){
                if(empty($code)){
                    return array('code'=>0,'msg'=>' 请输入验证码！');
                }
                $check=$_SESSION['check'][$data['mobile']];
                if($check!=$code){
                    return array('code' => 0, 'msg' => '验证码不正确');
                }
            }
            if(!$nickname || !$password){
                return array('code'=>0,'msg'=>'请填写账号或密码');
            }
         /*   if(empty($username )){
                return array('code'=>-1,'msg'=>'请输入姓名');
            }
            $info['username']=$username;*/
           /* $province =explode(':',$data['province']);
            $data['province'] = isset( $province[1])?$province[1]:'';
            $city =explode(':',$data['city']);
            $data['city'] = isset( $city[1])?$city[1]:'';
            $district =explode(':',$data['district']);
            $data['district'] = isset( $district[1])?$district[1]:'';

            if($data['province']==null ||$data['city']==null ||$data['district']==null){
                return array('code'=>0,'msg'=>'请选择联系地址');
            }
            $info['province']=$data['province'];
            $info['city']=$data['city'];
            $info['district']=$data['district'];
            if(empty( $data['dizhi'] )){
                return array('code'=>-1,'msg'=>'请输入收货地址');
            }
            $info['dizhi']= $data['dizhi'];*/


         /*   if(empty($shenfenzheng )){
                return array('code'=>-1,'msg'=>'请输入身份证号');
            }
            $info['shenfenzheng']=$shenfenzheng;*/
            $user = db('users')->where("nickname",$nickname)->find();
            if($user){
                return array('code'=>0,'msg'=>'账号已存在!');
            }
            $info['nickname']=$nickname;
            $user = db('users')->where("mobile",$mobile)->find();
            if($user){
                return array('code'=>0,'msg'=>'手机号已存在!');
            }
            $info['mobile']=$mobile;

            if(empty($password)){
                return array('code'=>0,'msg'=>'密码不能为空!');
            }else{
                if($password!=$data['password2']){
                    return array('code'=>0,'msg'=>'密码输入不一致!');
                }
                $alen=strlen($password);
                if($alen<6||$alen>12){
                    return array('code'=>-1,'msg'=>'请输入6-12位的密码');
                }

                $info['password']=md5($password);
            }

            if(empty($twopassword)){
                return array('code'=>0,'msg'=>'交易密码不能为空!');
            }else{
                if($twopassword!=$data['twopassword2']){
                    return array('code'=>0,'msg'=>'交易密码输入不一致!');
                }
                $alen2=strlen($twopassword);
                if($alen2<6||$alen2>12){
                    return array('code'=>-1,'msg'=>'请输入6-12位的密码');
                }
                $info['twopassword']=md5($twopassword);
            }
            if(empty($topmobi)){
                return array('code'=>0,'msg'=>'推荐人编号不能为空！！！');
            }else{
                $reus = db('users')->where(array('nickname'=>$topmobi,'activation'=>1))->find();
                if(empty($reus)){
                    return array('code'=>0,'msg'=>'推荐人不存在或者未激活！');
                }else{
                    $rpath="".$reus['rpath'].$reus['id'].",";
                    $info['up_userid']=$reus['id'];
                    $info['rpath']=$rpath;
                    $info['relevel']=$reus['relevel']+1;
                }

            }
            if($sys['anzhi']=='open') {
                if (empty($fathername)) {
                    return array('code' => 0, 'msg' => '安置人编号不能为空！！！');
                } else {
                    $father = db('users')->where(array('nickname' => $fathername, 'activation' => 1))->find();
                    if (empty($father)) {
                        return array('code' => 0, 'msg' => '安置人不存在或者未激活！');
                    } else {
                        $is_user = db('users')->where('fatherid', $father['id'])->where('treeplace', $treeplace)->find();
                        if (empty($is_user)) {
                            $ppath = "" . $father['ppath'] . $father['id'] . ",";
                            $info['fatherid'] = $father['id'];
                            $info['ppath'] = $ppath;
                            $info['plevel'] = $father['plevel'] + 1;
                        } else {
                            return array('code' => 0, 'msg' => '该位置已有会员，请更换位置后注册！');
                        }

                    }
                }
            }

            /*             if(empty($centermobile)){
                              return array('code'=>0,'msg'=>'服务中心编号不能为空！！！');
                          }else{
                              $server = db('users')->where(array('nickname'=>$centermobile,'activation'=>1,'server'=>2))->find();
                              if(empty($server)){
                                  return array('code'=>0,'msg'=>'服务中心不存在或者未激活！');
                              }else{
                                  $info['center_id']=$server['id'];
                              }
                          }*/
            $info['reg_time'] = time();
            $info['treeplace'] = $treeplace;
            $uid = db('users')->insertGetId($info);
            db('users')->where('id',$uid)->setField('uid',$uid);
            if($sys['anzhi']=='open') {
                if ($treeplace == 1) {
                    db('users')->where('id', $father['id'])->setField('leftid', $uid);
                } else {
                    db('users')->where('id', $father['id'])->setField('rightid', $uid);
                }
            }
            return array('code'=>1,'msg'=>'注册成功','url' => url('index/index'));

        }
        return view();
    }

    //注册协议
    public function the_registration_agreement(){
        $article=db('page')->where('id',18)->find();
        $this->assign('article',$article);
        return view();
    }
    public function reg(){
        if(Request::isAjax()) {
            $data = input('post.');
            if($this->sys['code']=='open') {
                $code = $data['vercode'];
                if (!$this->check($code)) {
                    return array('code' => 0, 'msg' => '验证码错误');
                }
            }
            $is_validated = 0 ;
            if(is_email($data['email'])){
                $is_validated = 1;
                $data['email_validated'] = 1;
                if(get_user_info($data['email'],1)){
                    return array('code'=>-1,'msg'=>'邮箱账号已存在');
                }
            }
            if(is_mobile_phone($data['email'])){
                $is_validated = 1;
                $data['mobile_validated'] = 1;
                $data['mobile'] = $data['email']; //手机注册
                unset($data['email']);
                if(get_user_info($data['mobile'],2)){
                    return array('code'=>-1,'msg'=>'手机账号已存在');
                }
            }
            $check=$_SESSION['check'][$data['mobile']];
            if($check!=$data['code']){
                return array('code' => 0, 'msg' => '验证码不正确');
            }
            if(empty($data['up_userid'])){
/*                $user=db('users')->where(array('mobile'=>18353999999,'activation'=>1))->find();
                if(empty($user)){
                    return array('code'=>-1,'msg'=>'该推荐人不存在或者未激活');
                }else{
                    $rpath="".$user['rpath'].$user['id'].",";
                    $data['rpath']=$rpath;
                    $data['up_userid']=$user['id'];
                }*/
                return array('code'=>-1,'msg'=>'请输入推荐人手机号');
            }else{
                $user=db('users')->where(array('mobile'=>$data['up_userid'],'activation'=>1))->find();
                if(empty($user)){
                    return array('code'=>-1,'msg'=>'该推荐人不存在或者未激活');
                }else{
                    $rpath="".$user['rpath'].$user['id'].",";
                    $data['rpath']=$rpath;
                    $data['up_userid']=$user['id'];
                }
            }

            if(empty($data['fathername'])){
                return array('code'=>-1,'msg'=>'请输入安置人手机号');
            }else{
                $father=db('users')->where(array('mobile'=>$data['fathername'],'activation'=>1))->find();
                if(empty($father)){
                    return array('code'=>-1,'msg'=>'该安置人不存在或者未激活');
                }else{
                    $where=array(
                        'fatherid'=>$father['id'],
                        'treeplace'=>$data['treeplace']
                    );
                    $is_user=db('users')->where($where)->find();
                    if(empty($is_user)){
                        $rpath="".$father['ppath'].$father['id'].",";
                        $data['ppath']=$rpath;
                        $data['fatherid']=$father['id'];
                        $data['plevel']=$father['plevel']+1;
                    }else{
                        return array('code'=>0,'msg'=>'该位置已有会员，请更换位置后注册！');
                    }

                }
            }
            if(empty($data['treeplace'])){
                return array('code'=>-1,'msg'=>'请选择安置区域');
            }
            if(empty($data['level'])){
                return array('code'=>-1,'msg'=>'请选择报单级别');
            }
/*            if(empty($data['center_id'])){
                $serverid=db('users')->where(array('mobile'=>18353999999,'activation'=>1,'server'=>2))->value('id');
                if(empty($serverid)){
                    return array('code'=>-1,'msg'=>'该服务中心不存在或者未激活');
                }else{
                    $data['center_id']=$serverid;
                }
               // return array('code'=>-1,'msg'=>'请输入服务中心手机号');
            }else{
                $serverid=db('users')->where(array('mobile'=>$data['center_id'],'activation'=>1,'server'=>2))->value('id');
                if(empty($serverid)){
                    return array('code'=>-1,'msg'=>'该服务中心不存在或者未激活');
                }else{
                    $data['center_id']=$serverid;
                }
            }*/
            if($is_validated != 1){
                return array('code'=>0,'msg'=>'请用手机号注册');
            }
            if(!$data['username'] || !$data['password']){
                return array('code'=>-1,'msg'=>'请输入昵称或密码');
            }
            if(empty($data['shenfenzheng'])){
                return array('code'=>-1,'msg'=>'请输入身份证号');
            }
            $alen=strlen($data['password']);
            if($alen<6||$alen>12){
                return array('code'=>-1,'msg'=>'请输入6-12位的密码');
            }
            //验证两次密码是否匹配
            if($data['password'] != $data['password2']){
                return array('code'=>-1,'msg'=>'两次输入密码不一致');
            }
            if(empty($data['center_id'])){
                 return array('code'=>-1,'msg'=>'请输入服务中心手机号');
            }else{
                $serverid=db('users')->where(array('mobile'=>$data['center_id'],'activation'=>1,'server'=>2))->value('id');
                if(empty($serverid)){
                    return array('code'=>-1,'msg'=>'该服务中心不存在或者未激活');
                }else{
                    $data['center_id']=$serverid;
                }
            }
            unset($data['password2']);
            unset($data['vercode']);
            //验证是否存在用户名

            $data['password'] = md5($data['password']);
            $data['reg_time'] = time();
            $id = db('users')->insertGetId($data);
            if($id === false){
                return array('code'=>-1,'msg'=>'注册失败');
            }
            db('users')->where('id',$id)->setField('uid',$id);
            if($data['treeplace']==1){
                db('users')->where('id',$father['id'])->setField('leftid',$id);
            }else{
                db('users')->where('id',$father['id'])->setField('rightid',$id);
            }
            $user = db('users')->field('id,username')->where("id", $id)->find();
            session('user',$user);
            achievement(0,0,1,1,0,0,0,0,0);
            return array('code'=>1,'msg'=>'注册成功','result'=>$user);
        }else {
            $levels=db('user_level')->where('level_id','gt',0)->select();
            $id=input('id');
            if(!empty($id)){
                $user=getuser($id);
            }
            $this->assign('mobile', $user['mobile']);
            $plugin = db('plugin')->where(['type' => 'login', 'status' => 1])->select();
            $this->assign('levels', $levels);
            $this->assign('plugin', $plugin);

            $this->assign('title', '会员注册');
            return $this->fetch();
        }
    }

    public function forget(){
        if(request()->isPost()) {
            $data = input('post.');
            if(empty($data['code'])){
                return array('code' => 0, 'msg' => '请输入验证码');
            }
            if(empty($data['mobile'])){
                return array('code' => 0, 'msg' => '请输入手机号');
            }
            if(empty($data['nickname'])){
                return array('code' => 0, 'msg' => '请输入会员编号');
            }
            $check=$_SESSION['check'][$data['mobile']];
            if($check!=$data['code']){
                return array('code' => 0, 'msg' => '验证码不正确');
            }
            $user=db('users')->where('mobile',$data['mobile'])->find();
            if(empty($user)){
                return array('code'=>0,'msg'=>'该手机号不存在！');
            }else{
                $array=array(
                    'password'=>md5(input('password')),
                    'twopassword'=>md5(input('twopassword')),
                );
                db('users')->where('nickname',$data['nickname'])->update($array);
                return array('code'=>1,'msg'=>'密码找回成功！');
            }

        }else{
            $this->assign('title','忘记密码');
            return $this->fetch();
        }
    }
    /**
     * 发送邮件验证码
     * @param $sender 接收人
     * @return json
     */
    public function sendEmail(){
        if(request()->isPost()) {
            $sender = input('email');
            $sms_time_out = 180;
            //获取上一次的发送时间
            $send = session('validate_code');
            if (!empty($send) && $send['time'] > time() && $send['sender'] == $sender) {
                //在有效期范围内 相同号码不再发送
                return json(['code' => -1, 'msg' => '规定时间内,不要重复发送验证码']);
            }
            $code = mt_rand(1000, 9999);
            //检查是否邮箱格式
            if (!is_email($sender)) {
                return json(['code' => -1, 'msg' => '邮箱码格式有误']);
            }
            $send = send_email($sender, '验证码', '您好，你的验证码是：' . $code);
            if ($send) {
                $info['code'] = $code;
                $info['sender'] = $sender;
                $info['is_check'] = 0;
                $info['time'] = time() + $sms_time_out; //有效验证时间
                session('validate_code', $info);
                return json(['code' => 1, 'msg' => '验证码已发送，请注意查收']);
            }else{
                return array('code' => -1, 'msg' => '验证码发送失败,请联系管理员');
            }
        }else{
            return json(['code' => -1, 'msg' => '非法请求']);
        }
    }
    public function duanxin2(){
        /*
        ***聚合数据（JUHE.CN）短信API服务接口PHP请求示例源码
        ***DATE:2015-05-25
    */
        header('content-type:text/html;charset=utf-8');
        $mobile=input('mobile');
        $type=input('type');
        if($type==1){
            $tpl_id=150453;
        }elseif($type==2){
            $tpl_id=150452;
        }else{
            $tpl_id=150454;
        }

        $sendUrl = 'http://v.juhe.cn/sms/send'; //短信接口的URL
        $code=rand('1000','9999');
        $smsConf = array(
            'key'   => '424aa6720b2ffa5c24399d94dc91a1af', //您申请的APPKEY
            'mobile'    =>$mobile, //接受短信的用户手机号码
            'tpl_id'    =>$tpl_id, //您申请的短信模板ID，根据实际情况修改
            'tpl_value' =>'#code#='.$code //您设置的模板变量，根据实际情况修改
            //  'tpl_value' =>'#code#=1234&#company#=聚合数据' //您设置的模板变量，根据实际情况修改
        );
        session_start();
//        $_SESSION[$mobile]=$code;
        $_SESSION['check'][$mobile]=$code;
        $content =$this->juhecurl1($sendUrl,$smsConf,1); //请求发送短信

        if($content){
            $result = json_decode($content,true);
            $error_code = $result['error_code'];
            if($error_code == 0){
                //状态为0，说明短信发送成功
                //     echo "短信发送成功,短信ID：".$result['result']['sid'];
                echo  json_encode(array('success'=>1,'msg'=>'短信发送成功'));exit;
            }else{
                //状态非0，说明失败
                $msg = $result['reason'];
                echo  json_encode(array('success'=>0,'msg'=>'短信发送失败'));exit;
                //     echo "短信发送失败(".$error_code.")：".$msg;
            }
        }else{
            //返回内容异常，以下可根据业务逻辑自行修改
            //   echo "请求发送短信失败";
            echo  json_encode(array('success'=>0,'msg'=>'请求发送短信失败'));exit;
        }
    }

    /**
     * 请求接口返回内容
     * @param  string $url [请求的URL地址]
     * @param  string $params [请求的参数]
     * @param  int $ipost [是否采用POST形式]
     * @return  string
     */
    function juhecurl1($url,$params=false,$ispost=0){
        $httpInfo = array();
        $ch = curl_init();
        curl_setopt( $ch, CURLOPT_HTTP_VERSION , CURL_HTTP_VERSION_1_1 );
        curl_setopt( $ch, CURLOPT_USERAGENT , 'Mozilla/5.0 (Windows NT 5.1) AppleWebKit/537.22 (KHTML, like Gecko) Chrome/25.0.1364.172 Safari/537.22' );
        curl_setopt( $ch, CURLOPT_CONNECTTIMEOUT , 30 );
        curl_setopt( $ch, CURLOPT_TIMEOUT , 30);
        curl_setopt( $ch, CURLOPT_RETURNTRANSFER , true );
        if( $ispost )
        {
            curl_setopt( $ch , CURLOPT_POST , true );
            curl_setopt( $ch , CURLOPT_POSTFIELDS , $params );
            curl_setopt( $ch , CURLOPT_URL , $url );
        }
        else
        {
            if($params){
                curl_setopt( $ch , CURLOPT_URL , $url.'?'.$params );
            }else{
                curl_setopt( $ch , CURLOPT_URL , $url);
            }
        }
        $response = curl_exec( $ch );
        if ($response === FALSE) {
            //echo "cURL Error: " . curl_error($ch);
            return false;
        }
        $httpCode = curl_getinfo( $ch , CURLINFO_HTTP_CODE );
        $httpInfo = array_merge( $httpInfo , curl_getinfo( $ch ) );
        curl_close( $ch );
        return $response;
    }

    public function duanxin(){
        header("Content-type:text/html;charset=utf-8");
        $tel=input('mobile');
        $code=rand('1000','9999');
        session_start();
        $_SESSION['check'][$tel]=$code;
        $success_str = '您的验证码是：'.$code.'【嘉华国际】';
        //$success_str=input('success_str');
        $uid = "NJLKJ0006418";
        $passwd = "zh9527@";
//修改密码信息
        $msg = rawurlencode(mb_convert_encoding($success_str, "gb2312", "utf-8"));
        $request_url = "https://mb345.com/ws/BatchSend2.aspx?CorpID=".$uid."&Pwd=".$passwd."&Mobile=".$tel;
        $gateway = $request_url."&Content=".$msg."&Cell=&SendTime=";
        $result= httpRequest($gateway,'GET');
        //   $result = file_get_contents($gateway);
        if($result>0){
            echo  json_encode(array('success'=>1));exit;
        }else{
            echo  json_encode(array('success'=>0));exit;
        }
        exit;
    }
}